<template>
  <div v-if="!fetching">
    <van-nav-bar
        title="发布笔记"
        fixed
        left-arrow
        @click-left="goBack()"
    />
    <div style="padding: 8vh 0 0 0">
      <van-field name="imgs" label="图像">
        <template #input>
          <van-uploader 
						v-model="form.imgs" 
						:max-count="maxCount" 
						:after-read="afterRead" 
						:before-delete="beforeDelete"
						:before-read="beforeRead"
						:accept="fileType"
					/>
        </template>
      </van-field>

      <van-field
          readonly
          clickable
          name="channelId"
          :value="note.channelName"
          label="频道"
          placeholder="点击选择频道"
          @click="form.showPicker = true"
      />
      <van-popup v-model="form.showPicker" position="bottom">
        <van-picker
            show-toolbar
            :columns="channels"
            value-key="name"
            @confirm="onConfirm"
            @cancel="form.showPicker = false"
        >
        </van-picker>
      </van-popup>

      <van-field
          v-model="note.title"
          name="title"
          label="标题"
          placeholder="请输入标题"
          maxlength="15"
          show-word-limit
          :rules="[{ required: true, message: '请输入标题' }]"
      />

      <van-field
          v-model="note.text"
          rows="2"
          autosize
          name="text"
          label="正文"
          type="textarea"
          maxlength="200"
          placeholder="请输入正文"
          show-word-limit
					v-if="note.channelId !== '1003'"
      />

      <div style="display: flex;justify-content: space-around;margin-top: 2vh">
        <!-- <van-button round style="width: 20vw" type="info" @click="draftNote">存草稿</van-button> -->
        <van-button round style="width: 50vw" type="primary" @click="publishNote">发布笔记</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import Tabbar from "../components/Tabbar";
import { mapMutations } from "vuex";

function Channel(c) {
  this.id = c.id;
  this.name = c.name;
}

function Note(n) {
  this.imgs = n.imgs;
  this.channelId = n.channelId;
  this.id = n.id;
  this.text = n.text;
  this.title = n.title;
}

export default {
  components: {Tabbar},
  data() {
    return {
      fetching: true,
      isExist: false,
      channelMap: new Map(),
      channels: [],
      note: {
        imgs: [],
        channelId: "",
        channelName: "",
        id: "",
        text: "",
        title: "",
      },
      form: {
        showPicker: false,
        imgs: []
      },
			isAdmin: false,
			maxCount: 5,
    }
  },
	computed: {
		fileType: function() {
			if(this.note.channelId === '1003'){
				return 'video/*';
			}
			return 'image/*';
		}
	},
  methods: {
    ...mapMutations(["removeToken"]),
    saveNote(type) {
      this.http.post(type ? "/api/hyc/note/publish" : "/api/hyc/note/draft/add", {
        channelId: this.note.channelId,
        id: this.note.id,
        imgs: this.note.imgs,
        text: this.note.text,
        title: this.note.title,
      }).then(() => {
        this.goBack()
      });
    },
    publishNote() {
      this.saveNote(true);
    },
    draftNote() {
      this.saveNote(false);
    },
    goBack() {
      this.$router.go(-1);
    },
    beforeDelete(file, detail) {
      this.note.imgs.splice(detail.index, 1);
      return true
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
			if(file.file.type.indexOf('video') === 0){
				this.maxCount = 1;
			}
      let formData = new FormData()
      formData.append("file", file.file)
      this.http.post("/api/hyc/file/upload", formData).then((res) => {
        this.note.imgs.push(res.data.data);
      }).catch((err) => {
				this.$toast("文件最大不超过10M");
			});
    },
    onConfirm(value) {
      this.note.channelName = value.name;
      this.note.channelId = value.id;
      this.form.showPicker = false;
    },
    noteDetail() {
      return this.http.get("/api/hyc/note/detail" + "?noteId=" + this.note.id)
          .then(res => {
            let temp = new Note(res.data.data);
            this.note = temp;
            this.note.channelName = this.channelMap.get(temp.channelId).name;
            this.form.imgs = temp.imgs.map((o) => {
              return {url: o}
            });
          })
    },
    listChannel() {
      return this.http.get("/api/hyc/channel/list").then(res => {
				let list = res.data.data;
				if(!this.isAdmin){
					list = list.filter((item) => {
						return item.id !== '1002' && item.id !== '1004';
					});
				}
				console.log('list', this.isAdmin,list)
        list.forEach((channel) => {
          let temp = new Channel(channel);
          this.channels.push(temp);
          this.channelMap.set(channel.id, temp);
        });
      });
    },
		userDetail() {
      this.http.get("/api/phx/user/detail?userId=").then((res) => {
        this.isAdmin = res.data.data.isAdmin;
				this.listChannel().then(() => {
					if (this.isExist) {
						this.noteDetail();
					}
					}).finally(() => {
						this.fetching = false
					})
      });
    },
		beforeRead(file) {
			console.log('file', this.note.channelId,file)
			if(this.note.channelId === ''){
				this.$toast('请先选择频道！');
				return false;
			}
			if(this.note.channelId === '1003' && file.type.indexOf('video') === -1){
				this.$toast('请上传视频！');
				return false;
			}
			if(this.note.channelId === '1004' && file.type.indexOf('video') === 0){
				this.$toast('暂不提供在该频道上传视频！');
				return false;
			}
			return true;
		},
  },
  mounted() {
    if (this.$route.query.id === undefined) {
      this.note.id = "";
      this.isExist = false;
    } else {
      this.note.id = this.$route.query.id;
      this.isExist = true;
    }
		this.userDetail()
  },
}
</script>
<style lang="scss" scoped></style>

